#include "libfile.hpp"
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;

string losu_file_strrt;
vector<int> fileptr;
vector<fstream> _filesm;
int  losuFileFreefile();
void losuFileOpen(int num,string mod,string file);
void losuStdError(string er);

extern "C"{
    LNI losu_file_open(LNI file,LNI mod){
        losu_file_rt[0]='\0';
        int ptr = losuFileFreefile();
        sprintf(losu_file_rt,"%d",ptr);
        losuFileOpen(ptr,mod,file);    
        return losu_file_rt;    
    }
    LNI losu_file_close(LNI num){
        losu_file_rt[0]='\0';
        _filesm[atoi(num)].close();
        return losu_file_rt;   
    }
    LNI losu_file_lineinput(LNI num){
        getline(_filesm[atoi(num)],losu_file_strrt);
        return (char*)(losu_file_strrt.c_str());
    }
    LNI losu_file_input(LNI num){
        _filesm[atoi(num)]>>losu_file_strrt;
        return (char*)(losu_file_strrt.c_str());
    }
    LNI losu_file_write(LNI num,LNI str){
        _filesm[atoi(num)]<<str;
        losu_file_rt[0]='\0';
        return losu_file_rt;
    }
    LNI losu_file_eof(LNI num){
        losu_file_rt[0]='\0';
        sprintf(losu_file_rt,"%d",_filesm[atoi(num)].eof());
        return losu_file_rt;
    }
}
int losuFileFreefile(){
    for(int i=0;i<fileptr.size();i++){
        if(fileptr[i]==0){
            fileptr[i]=1; return i;
        }
    }
    fileptr.push_back(1);
    return fileptr.size()-1;
}
void losuFileOpen(int num,string mod,string file){
    while(num>=_filesm.size())
        _filesm.push_back(fstream());    
    
    
    if(mod=="新建") 
        _filesm[num].open(file,ios::out);
    else if(mod=="追加") 
        _filesm[num].open(file,ios::app);
    else if(mod=="读取") 
        _filesm[num].open(file,ios::in);
    else
        losuStdError("无法打开文件 '"+file+"'");

        
    if(_filesm[num].is_open()==0)
        losuStdError("无法打开文件 '"+file+"'");

}
void losuStdError(string er){
    cout<<er<<endl;
}